'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { getAvatarUrl } from '@/lib/utils'

export default function TestProxyPage() {
  const [testPath, setTestPath] = useState('/uploads/avatars/test.jpg')
  const [proxyUrl, setProxyUrl] = useState('')
  const [directUrl, setDirectUrl] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    // 设置测试URL
    const backendUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000'
    const baseUrl = backendUrl.endsWith('/api') ? backendUrl.replace('/api', '') : backendUrl
    setDirectUrl(`${baseUrl}${testPath}`)
    setProxyUrl(`/api/proxy${testPath}`)
  }, [testPath])

  const testProxy = async () => {
    setLoading(true)
    setError('')
    
    try {
      const response = await fetch(proxyUrl)
      if (response.ok) {
        console.log('代理请求成功:', response.status)
      } else {
        setError(`代理请求失败: ${response.status} ${response.statusText}`)
      }
    } catch (err) {
      setError(`代理请求错误: ${err}`)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div>
        <h1 className="text-3xl font-bold">图片代理测试</h1>
        <p className="text-muted-foreground">测试 Next.js 图片代理功能</p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>代理配置测试</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-2">测试路径</label>
            <Input
              value={testPath}
              onChange={(e) => setTestPath(e.target.value)}
              placeholder="/uploads/avatars/test.jpg"
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium mb-2">直接访问URL</label>
              <Input value={directUrl} readOnly className="text-xs" />
              <p className="text-xs text-muted-foreground mt-1">
                这可能会因为跨域而失败
              </p>
            </div>

            <div>
              <label className="block text-sm font-medium mb-2">代理URL</label>
              <Input value={proxyUrl} readOnly className="text-xs" />
              <p className="text-xs text-muted-foreground mt-1">
                通过 Next.js 代理访问
              </p>
            </div>
          </div>

          <Button onClick={testProxy} disabled={loading}>
            {loading ? '测试中...' : '测试代理'}
          </Button>

          {error && (
            <div className="p-3 bg-red-50 border border-red-200 rounded-md">
              <p className="text-red-800 text-sm">{error}</p>
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>头像组件测试</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center space-x-4">
            <div>
              <p className="text-sm font-medium mb-2">使用代理路径</p>
              <Avatar className="h-16 w-16">
                <AvatarImage src={proxyUrl} alt="测试头像" />
                <AvatarFallback>测</AvatarFallback>
              </Avatar>
            </div>

            <div>
              <p className="text-sm font-medium mb-2">使用直接路径</p>
              <Avatar className="h-16 w-16">
                <AvatarImage src={directUrl} alt="测试头像" />
                <AvatarFallback>测</AvatarFallback>
              </Avatar>
            </div>
          </div>

          <div className="text-sm text-muted-foreground">
            <p>• 代理路径应该能正常显示图片</p>
            <p>• 直接路径可能会因为跨域而显示失败</p>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>环境变量信息</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-2 text-sm">
            <p><strong>NEXT_PUBLIC_API_URL:</strong> {process.env.NEXT_PUBLIC_API_URL || '未设置'}</p>
            <p><strong>Node环境:</strong> {process.env.NODE_ENV || '未知'}</p>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
